<?php 
class Mobile extends CI_Controller {
    
    private $_privateKey = "65asdfu56asdf";
    
	public function __construct() {
		parent::__construct();
		
		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->model('Jobs');
		$this->load->model('Company');
		$this->load->model('Rinvoices');
	}
	
	public function index() {
		redirect('/');
	}
        
        public function auth()
        {
            $result = array(
                'status' => 0,
                'message' => "Login fail",
                'data' => array()
            );
            
            $email = @$_REQUEST['email'];
            $password = @$_REQUEST['password'];
            $token = @$_REQUEST['token'];
            
            // generate token will use later
            $checkToken = md5($this->_privateKey . $email . $password);
            
            $user =& Users::getInstance();
            
            if ($user->login($email, $password, 0)) {    
                    $user =& Users::getInstance();
                    $result = array(
                        'status' => 1,
                        'message' => "Login successfully",
                        'data' => $user
                    );
            }
            
            echo json_encode($result);
        }
        
        public function getjob() {
            $jobid = @$_REQUEST['jobid'];
            $job = $this->Jobs->getJob($jobid, false);
            if($job) {
                $result = array(
                        'status' => 1,
                        'message' => "Get job successfully",
                        'data' => $job
                    );
            } else {
                $result = array(
                        'status' => 1,
                        'message' => "Job ID is not match",
                        'data' => $job
                    );
            }
            echo json_encode($result);
        }
        
        public function dashboard()
        {            
		$this->load->helper('url');
		$this->load->library('Menu');				
		$data = array();
		$uid = @$_REQUEST['uid'];
                
                $result = array(
                    'status' => 0,
                    'message' => "User ID is required"
                );
                if(!$uid) {
                    echo json_encode($result);die;
                }
                
                $userObj =& Users::getInstance();
                $user = $userObj->getUserInfo($uid);
                if(!$user){
                    $result = array(
                        'status' => 0,
                        'message' => "User is not found"
                    );
                    echo json_encode($result);die;
                }
                
		// Check if user is logged - display dashboard
		if ($user->id > 0) {
			$this->load->model('Jobs');
			$data['user'] = $user;			
			if ($user->level > 0) {	
				$data['needquote'] = $this->Jobs->getNeedQuote();
				$data['needquoteCount'] = $this->Jobs->getNeedQuote(-1, true);
				$data['needquotePages'] = $this->Jobs->getPages($data['needquoteCount'], 5);
				$data['needconfirm'] = $this->Jobs->getNeedConfirm();
				$data['needconfirmCount'] = $this->Jobs->getNeedConfirm(-1, true);
				$data['needconfirmPages'] = $this->Jobs->getPages($data['needconfirmCount'], 5);
				$data['oncoming'] = $this->Jobs->getOncoming(-1);
				$data['oncomingCount'] = $this->Jobs->getOncoming(-1, true);
				$data['oncomingPages'] = $this->Jobs->getPages($data['oncomingCount'], 5);
				$data['completed'] = $this->Jobs->getCompleted(-1);
				$data['completedCount'] = $this->Jobs->getCompletedCount(-1);
				$data['completedPages'] = $this->Jobs->getPages($data['completedCount'], 5);
				$data['cancelled'] = $this->Jobs->getCancelled(-1);
				$data['cancelledCount'] = $this->Jobs->getCancelledCount(-1);
				$data['cancelledPages'] = $this->Jobs->getPages($data['cancelledCount'], 5);
				
				$data['dueCount'] = $this->Jobs->getDueCount(-1);
				$data['overdueCount'] = $this->Jobs->getOverdueCount(-1);
				$data['overduetotal'] = $this->Jobs->getOverduePrice(-1);
				$data['dueOverduePages'] = $this->Jobs->getPages($data['dueCount'] + $data['overdueCount'], 5);
				
				$data['overdue'] = $this->Jobs->getOverduePriceList(-1);				
				$data['stats']['oncoming'] = $this->Jobs->getOncoming(-1, true);
				$data['stats']['quote'] = $this->Jobs->getNeedQuote(-1, true);			
			} else {
				$data['oncoming'] = $this->Jobs->getOncoming($user->id);
				$data['oncomingCount'] = $this->Jobs->getOncoming($user->id, true);
				$data['oncomingPages'] = $this->Jobs->getPages($data['oncomingCount'], 5);
				$data['completed'] = $this->Jobs->getCompleted($user->id);
				$data['completedCount'] = $this->Jobs->getCompletedCount($user->id);
				$data['completedPages'] = $this->Jobs->getPages($data['completedCount'], 5);
				$data['cancelled'] = $this->Jobs->getCancelled($user->id);
				$data['cancelledCount'] = $this->Jobs->getCancelledCount($user->id);
				$data['cancelledPages'] = $this->Jobs->getPages($data['cancelledCount'], 5);
				$data['drafts'] = $this->Jobs->getDrafts($user->id);
				$data['draftsCount'] = $this->Jobs->getDrafts($user->id, true);
				$data['draftsPages'] = $this->Jobs->getPages($data['draftsCount'], 5);
				$data['dueCount'] = $this->Jobs->getDueCount($user->id);
				$data['overdueCount'] = $this->Jobs->getOverdueCount($user->id);
				$data['overduetotal'] = $this->Jobs->getOverduePrice($user->id);
				$data['dueOverduePages'] = $this->Jobs->getPages($data['dueCount'] + $data['overdueCount'], 5);				
				$data['overdue'] = $this->Jobs->getOverduePriceList($user->id);								
			}
                        
                        $result = array(
                            'status' => 1,
                            'message' => "Get data successfully",
                            'data' => $data
                        );
                        echo json_encode($result);die;
		} else {
                    $result = array(
                        'status' => 0,
                        'message' => "Unknown user"
                    );
                    echo json_encode($result);die;
                }                
    }
    
    public function support_send()
    {        
        $this->load->helper('form');        
        $this->load->helper('security');
        $this->load->library('email');    
		
		// intial email
		$mailconf['mailtype'] = 'html';
		$this->email = new CI_Email($mailconf);
		
        $fromemail = $_REQUEST['email'];
        $name = $_REQUEST['name'];
        $subject = $_REQUEST['name'];
        $msg = $_REQUEST['msg'];
        
        $this->email->from($fromemail, $name);
        $this->email->to('ivy@bookabus.sg');

        $this->email->subject($subject);
        $this->email->message($msg);

        $message = '<p>Your contact form have been sent.</p>';

        $result = array(
                    'status' => 1,
                    'message' => "Your contact form have been sent."
                );
        echo json_encode($result);die;
    }
    
    public function edit_user()
    {
        $user =& Users::getInstance();
        $errors = $user->updateAccount(@$_REQUEST['uid'], @$_REQUEST['password'], @$_REQUEST['chpassword'], @$_REQUEST['name'], @$_REQUEST['address'], @$_REQUEST['phone'], @$_REQUEST['company_name']);
        if($errors['noErrors']){
            $result = array(
                        'status' => 1,
                        'message' => "Edit profile successfully"
                    );
            echo json_encode($result);die;
        } else {
            $result = array(
                        'status' => 0,
                        'message' => $errors
                    );
            echo json_encode($result);die;
        }
    }

    public function updatetriptime() {
	// http ://www.bookabus.sg/beta/mobile/triptimeadd?type=time&uid=<userid>&startdate=<startdate>&enddate=<enddate>&passangers=<passangers>&hours=<hours>&locObject=<locObject>&belongsto=<belongto>&editid=<editid>
        // http ://www.bookabus.sg/beta/mobile/triptimeadd?type=trip&uid=<userid>&from=<from>&passangers=<passangers>&return=<return>&locObject=<locObject>&returnch=<on/off>&returnres=<returnres>&startdate=<startdate>&belongsto=<belongto>&editid=<editid>

        $user =& Users::getInstance();
        $type = $_REQUEST['type'];
        $owner = $_REQUEST['uid'];
        $status = "ok";
        
        switch ($type)
        {
            case 'time':
            {
                        $formatJob = true;
                    
                        $editId = @$_REQUEST['editid']; //job id will be updated

                        $result = $this->Jobs->updateTime($_REQUEST['startdate'], $_REQUEST['enddate'], $_REQUEST['passangers'], $_REQUEST['hours'], $_REQUEST['locObject'], '', $owner, 0, $editId);

                        $orderId = @$_REQUEST['belongsto'];
                
                        if ($orderId > 0) {
                            $updateData = array(
                                                'belongs' => $orderId,
                                                );
                            
                            $this->db->where('id', $result);
                            $this->db->update('jobs', $updateData);
                        }
            }
                        //echo json_encode($result);die;
                        break;
            case 'trip':
            {
                        $formatJob = true;
                        $editId = @$_REQUEST['editid'];; //job id will be updated
                        $return = $_REQUEST['returnres'];
                
//                        updateTrip ($date, $passangers, $from, $to, $return, $moreinfo, $owner, $draft = 0, $return_time=0)
                        $result = $this->Jobs->updateTrip($_REQUEST['startdate'], $_REQUEST['passangers'], $_REQUEST['from'], $_REQUEST['locObject'], $return, '', $owner, 0);

                        $orderId = @$_REQUEST['belongsto'];
                        
                        if ($orderId > 0) {
                                $updateData = array(
                                        'belongs' => $orderId,
                                );

                                $this->db->where('id', $result);
                                $this->db->update('jobs', $updateData);
                        }
            }
                        break;
        }

        $datareturn = array(
            'status' => $status,
            'data' => $this->Jobs->getJob($result, $formatJob),
        );


	/**********************************/
	// Send email
	/*********************************/
	$this->load->library('email');
	
	// intial email
	$mailconf['mailtype'] = 'html';
	$this->email = new CI_Email($mailconf);
		
	$groupId = $orderId;
	$email = $user->username;
	$name = $user->name;
					
	$ji = $this->Jobs->getOrderJobs($groupId);
	$jobInfo = array();
	foreach ($ji as $route) {
		$jobInfo[] = nl2br($this->Jobs->formatJobInfo($route));
	}
	$jobInfo[] = '\r\nMore info: '. nl2br($this->input->post('moreinfo'));
					
	$this->email->from('ivy@bookabus.sg', 'Ivy');
	$this->email->to($email);
				
	$this->email->subject('Bookabus.sg – Job Order #'.$this->Jobs->getID($groupId).' Submitted!');
	$this->email->message('Hello, '.$name.',
				<br /><br />
		You have successfully submitted the following job order for quotation:
		<br /><br />
		'.implode("<br/>", $jobInfo).'
		<br /><br />
		Thank you for enquiring, we will revert soon with a quotation for your confirmation and we will notify you via e-mail as soon as this happens
		<br /><br />
		Best Regards,
		<br />Ivy'
                          );
	$this->email->send();
					
	// admin mail
	$this->email->reply_to($email);
	$this->email->from($email, $name);
	$this->email->to('ivy@bookabus.sg');
					
	$this->email->subject('Bookabus.sg – Quote request on job #'.$this->Jobs->getID($groupId));
    $mmessage = implode("<br/>", $jobInfo).'<br /><br />To reply or take action, click '.anchor('/joborder/'.$groupId, 'here');
    $this->email->message($mmessage);
	$this->email->send();

	
	/**********************************/
	// End send email
	/*********************************/
        
        // end of request quote
        $datareturn['job_order_id'] = $orderId;
        
        echo json_encode($datareturn);die;
    }
    
    public function triptimeadd(){
        // http://www.bookabus.sg/beta/mobile/triptimeadd?type=time&uid=<userid>&startdate=<startdate>&enddate=<enddate>&passangers=<passangers>&hours=<hours>&locObject=<locObject>
        // http://www.bookabus.sg/beta/mobile/triptimeadd?type=trip&uid=<userid>&from=<from>&passangers=<passangers>&return=<return>&locObject=<locObject>&returnch=<on/off>&returnres=<returnres>&startdate=<startdate>
        $user =& Users::getInstance();
        $type = $_REQUEST['type'];
        $owner = $_REQUEST['uid'];
        $status = "ok";
        switch ($type)
        {
                case 'time':
                    
                        $formatJob = true;
                    
                        $editId = 0;

                        $result = $this->Jobs->createTime($_REQUEST['startdate'], $_REQUEST['enddate'], $_REQUEST['passangers'], $_REQUEST['hours'], $_REQUEST['locObject'], '', $owner, 0, $editId);

                        $orderId = @$_REQUEST['belongsto'];
                        
                        if ($orderId > 0) {
                                $updateData = array(
                                        'belongs' => $orderId,
                                );

                                $this->db->where('id', $result);
                                $this->db->update('jobs', $updateData);
                        }
                        break;
                case 'trip':
                        $formatJob = true;
                        $editId = 0;
                        $return = $_REQUEST['returnres'];
                        $result = $this->Jobs->createTrip($_REQUEST['startdate'], $_REQUEST['passangers'], $_REQUEST['from'], $_REQUEST['locObject'], $return, '', $owner, 0, $editId);

                        $orderId = @$_REQUEST['belongsto'];
                        
                        if ($orderId > 0) {
                                $updateData = array(
                                        'belongs' => $orderId,
                                );

                                $this->db->where('id', $result);
                                $this->db->update('jobs', $updateData);
                        }
                        break;
                case 'term':
                        $formatJob = true;
                        $result = $this->Jobs->createTerm($_REQUEST['startdate'], '', $owner, 0);
                        break;                
        }

        $datareturn = array(
            'status' => $status,
            'data' => $this->Jobs->getJob($result, $formatJob)
        );
        
        // request quote
        if ($type == 'term') {
            
                $termId = $this->Jobs->createTerm($_REQUEST['startdate'], '', $owner, 0);
                
                $addType = "2";
                
        } elseif ($type == 'upload') {
                $addType = "3";
        } else {
                $addType = "0";
        }     
        
        $jobOrderId = $this->Jobs->jobOrder($owner, $_REQUEST['moreinfo'], $addType, $_REQUEST['draft']);                

        $isDraft = false;
        
        if ($_REQUEST['draft'] == "1") {
                $isDraft = true;
        }

        $this->Jobs->calcStartDate($jobOrderId);


	/**********************************/
	// Send email
	/*********************************/
	$this->load->library('email');
	$this->load->helper('email');
	$this->load->helper('security');
	
	// intial email
	$mailconf['mailtype'] = 'html';
	$this->email = new CI_Email($mailconf);
		
	$groupId = $jobOrderId;
	$email = $user->username;
	$name = $user->name;
	
	$ji = $this->Jobs->getOrderJobs($groupId);
	$jobInfo = array();
	foreach ($ji as $route) {
		$jobInfo[] = nl2br($this->Jobs->formatJobInfo($route));
	}
	$jobInfo[] = "\r\nMore info: ". nl2br($this->input->post('moreinfo'));
	
	$this->email->from('ivy@bookabus.sg', 'Ivy');
	$this->email->to($email);
				
	$this->email->subject('Bookabus.sg – Job Order #'.$this->Jobs->getID($job).' Submitted!');
    $mmessage = 'Hello, '.$name.',
        <br /><br />
        You have successfully submitted the following job order for quotation:
            <br /><br />
            '.implode("<br/>", $jobInfo).'
            <br /><br />
            <p>Thank you for enquiring, we will revert soon with a quotation for your confirmation and we will notify you via e-mail as soon as this happens.
                <br /><br />
                Best Regards,
                <br />Ivy';
	$this->email->message($mmessage);
	$this->email->send();
					
	// admin mail
	$this->email->reply_to($email);
	$this->email->from($email, $name);
	$this->email->to('ivy@bookabus.sg');
					
	$this->email->subject('Bookabus.sg – Quote request on job #'.$this->Jobs->getID($groupId));
                          
      $mmessage = implode("<br/>", $jobInfo).'<br /><br />To reply or take action, click '.anchor('/joborder/'.$groupId, 'here');
      $this->email->message($mmessage);
	$this->email->send();

	
	/**********************************/
	// End send email
	/*********************************/
        
        // end of request quote
        $datareturn['job_order_id'] = $jobOrderId;
        
        echo json_encode($datareturn);die;
		
    }
    
    public function getconversations($jid) {
        $this->load->model('Chats');
        $conversations = $this->Chats->getConversation($jid);
        $datareturn = array(
            'status' => true,
            'data' => $conversations
        );
        echo json_encode($datareturn);die;
    }
    
    public function addconversation() {
//         jid, uid, text, postdate, payment, type, paid
//        addconversation?jid=<jid>&uid=<uid>&text=<text>&payment=<payment>&type=<type>&paid=<paid>
        $this->load->model('Chats');
        $jid = $_REQUEST['jid'];
        $uid = $_REQUEST['uid'];
        $text = $_REQUEST['text'];
        $type = $_REQUEST['type'];
        $paid = $_REQUEST['paid'];
        $ptype = $_REQUEST['payment'];
        $this->Chats->post($jid, $uid, $text, $type, $paid, $ptype);
        $datareturn = array(
            'status' => true,
            'data' => $_REQUEST
        );
        echo json_encode($datareturn);die;
    }
                          
    
    public function acceptquoted() {
        echo 'aaa'; die;
        
        // Accept a job have job status * 1 - quoted a price
        
//        $jobid = $_REQUEST['jobid'];
//        $job = $this->Jobs->getJob($jobid, false);
//        
//          //Change job status to user accepted
//        $job->changeJobStatus($jobid, 3);
//                          
//          // Change job_group status to user accepted
//        $job->changeStatus($job->belongs, 3);
//                          
//        /********************
//         * Send email
//         *******************/
//          $this->load->library('email');
//          $this->load->helper('email');
//          $this->load->helper('security');
//          
//          // intial email
//          $mailconf['mailtype'] = 'html';
//          $this->email = new CI_Email($mailconf);
//          
//                          // Get job_group of job which need to accept
//          $job_group = $this->Jobs->getOrderJob( $job->belongs );
//                          
//          $email = $user->username;
//          $name = $user->name;
//          
////                          Hello Thuong Nguyen,
////                          
////                          We are happy that you have accepted our offer for Job Order #20121127-0023
////                          
////                          Total Price: SGD 11.00
////                          Due in advance: SGD 0.00
////                          
////                          You can pay the due amount, if any, via by clicking here.
////                          
////                          Best Regards,
////                          Ivy
//          
//          $this->email->from('ivy@bookabus.sg', 'Ivy');
//          $this->email->to($email);
//                          
////                              Bookabus.sg – Quote on Job #20121127-0023 Accepted!
//          $this->email->subject('Bookabus.sg – Quote on Job #'.$this->Jobs->getID($job_group).' Accepted!');
//          $this->email->message('Hello '.$name.',
//                                <br /><br />
//                                We are happy that you have accepted our offer for Job Order #'
//                                .$this->Jobs->getID($job_group).
//                                '
//                                <br /><br />
//                                Total Price: SGD '.
//                                
//                                $job_group->price
//                                
//                                .'Due in advance: SGD'.
//                                
//                                $job_group->paid
//                                
//                                .'You can pay the due amount, if any, via by clicking '.anchor('/joborder/'.$groupId, 'here'.
//                                
//                                .'
//                                <br /><br />
//                                Best Regards,
//                                <br />Ivy');
//            $this->email->send();
//                                
//            // admin mail
//            $this->email->reply_to($email);
//            $this->email->from($email, $name);
//            $this->email->to('ivy@bookabus.sg');
//            
//            $this->email->subject('Bookabus.sg – Quote on Job #'.$this->Jobs->getID($job_group).' Accepted!');
//            $this->email->message(
//                                  '
//                                  <br />
//                                  To reply or take action, click '.anchor('/joborder/'.$groupId, 'here'));
//              $this->email->send();
//              
//              
//              /**********************************/
//              // End send email
//              /*********************************/
//                                  
//          $datareturn = array(
//                              'status' => true,
//                              'data' => {
//                                    'job' => $job,
//                                    'job_group' => $job_group
//                              }
//                              );
//          echo json_encode($datareturn); die;
    }
}
?>